﻿using MetroDataApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Web.Http;
using CSRedis.Internal.IO;
using CSRedis;


namespace MetroDataApi.Controllers
{
    public class MonitorPointsGroupController : ApiController
    {
        public string Post([FromBody]string value)
        {
            if (value == null)
            {
                return JsonConvert.SerializeObject(new { success = 0, err = "post参数不能为空,检查你的post方法" });
            }
            try
            {
                JObject jsonData = JObject.Parse(value);
                var names = jsonData["names"].ToString().Split(',');
                var values = jsonData["values"].ToString().Split(',').ToList().Select(p => p == "" ? double.NaN : Convert.ToDouble(p)).ToArray();
                var prjId = jsonData["prjId"].ToObject<int>();
                var time = jsonData["time"].ToString();

                if (names.Length != values.Length)
                {
                    return JsonConvert.SerializeObject(new { success = 0, err = "values和names参数包含的数据个数不一致." });
                }


                var result = "";
                using (var db = new MetroDataDataContext())
                {
                    if (jsonData["psw"] == null || !MonitorPointController.uploadPswCheck(db, jsonData["psw"].ToString()))
                    {
                        return JsonConvert.SerializeObject(new { success = 0, err = "上传需要提供正确的授权码." });
                    }

                    var noDuplicateResults = names.Zip(values, (t, v) => new result
                    {
                        name = t,
                        value = v,
                        time = time
                    }).GroupBy(p => p.name).Select(t => new result()
                    {
                        name = t.Key,
                        value = t.First().value,
                        time = time
                    });

                    foreach (var p in noDuplicateResults)
                    {
                        if (!double.IsNaN(p.value))
                        {
                            var tempRe = MonitorPointController.uploadMonitorPoint(db, prjId, p, false);
                            if (tempRe.Length > 0)
                            {
                                result += tempRe + "\r\n";
                            }
                        }
                        else
                        {
                            result += p.name + "数值不能为空" + "\r\n";
                        }
                    }
                    db.SubmitChanges();

                    using (var redis = new RedisClient("localhost"))
                    {
                        var prjName = db.Projects.SingleOrDefault(p => p.PrjId == prjId).Name;
                        if (noDuplicateResults.Count() > 0)
                        {
                            var date = DateTime.Parse(noDuplicateResults.First().time);
                            var needNotify = ProjectReviewHelper.AfterMonitorPointsUpload(prjId, date);
                            var newUploadData = new
                            {
                                prjId = prjId,
                                date = noDuplicateResults.First().time,
                                prjName = prjName,
                                notify = needNotify ? 1 : 0
                            };
                            //发布新数据上传的通知
                            redis.Publish("metroProjects:newDataUpload", JsonConvert.SerializeObject(newUploadData));
                        }
                    }
                }

                return JsonConvert.SerializeObject(new { success = result.Length > 0 ? 0 : 1, err = result });
            }
            catch (Exception a)
            {
                return JsonConvert.SerializeObject(new { success = 0, err = a.Message });
            }
        }
    }
}
